package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.search.mapper.HmallMapper;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.PageDTO;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.HmallService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class HmallServiceImpl extends ServiceImpl<HmallMapper, Item> implements HmallService {
    @Resource
    private RestHighLevelClient client;
    @Override
    public PageDTO<ItemDoc> searchAll(RequestParams params) {
        SearchRequest request =new SearchRequest("hmall");
        buildBasicQuery(params,request);
        //判断是默认还是销量还是价格进行筛选排序
        if (StringUtils.isNotBlank(params.getSortBy()) && !StringUtils.equals("default",params.getSortBy())){
            if (StringUtils.equals("sold",params.getSortBy())){
                request.source().sort(params.getSortBy(), SortOrder.DESC);
            }else if (StringUtils.equals("price",params.getSortBy())){
                request.source().sort(params.getSortBy(),SortOrder.ASC);
            }
        }
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page-1)*size).size(size);
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hmall");
            buildBasicQuery(params, request);
            request.source().size(0);
            buildAggregation(request);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> categoryList = getStringList(aggregations,"categoryAgg");
            result.put("category",categoryList);
            List<String> brandList = getStringList(aggregations, "brandAgg");
            result.put("brand",brandList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getSuggestions(String key) {
        SearchRequest request= new SearchRequest("hmall");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
        ));
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            ArrayList<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hmall", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Item item = getById(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hmall").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(20));
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20));
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder bool =new BoolQueryBuilder();
        if (StringUtils.isBlank(params.getKey())){
            bool.must(QueryBuilders.matchAllQuery());
        }else {
            bool.must(QueryBuilders.matchQuery("all",params.getKey()));
        }
        if (StringUtils.isNotBlank(params.getCategory())){
            bool.filter(QueryBuilders.termQuery("category",params.getCategory()));
        }
        if (StringUtils.isNotBlank(params.getBrand())){
            bool.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        if (Objects.nonNull(params.getMinPrice()) && Objects.nonNull(params.getMaxPrice())){
            bool.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()*100).lte(params.getMaxPrice()*100));
        }
        // 2.算分控制
//        FunctionScoreQueryBuilder functionScoreQuery =
//                QueryBuilders.functionScoreQuery(
//                        // 原始查询，相关性算分的查询
//                        bool,
//                        // function score的数组
//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
//                                // 其中的一个function score 元素
//                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
//                                        // 过滤条件
//                                        QueryBuilders.termQuery("isAD", true),
//                                        // 算分函数
//                                        ScoreFunctionBuilders.weightFactorFunction(10)
//                                )
//                        });
//        request.source().query(functionScoreQuery);
        request.source().query(bool);
    }
    private  PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        SearchHits hitsList = response.getHits();
        long total = hitsList.getTotalHits().value;
        SearchHit[] hits = hitsList.getHits();
        List<ItemDoc> itemDocList =new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //如果有高亮标识，进行判断并获取应该高亮的对应属性
            if (Objects.nonNull(highlightFields)){
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField!=null) {
                    String name = highlightField.getFragments()[0].string();
                    itemDoc.setName(name);
                }
            }
            itemDocList.add(itemDoc);
        }
        PageDTO<ItemDoc> pageDTO = new PageDTO<ItemDoc>();
        pageDTO.setTotal(total);
        pageDTO.setList(itemDocList);
        return pageDTO;
    }

    private  List<String> getStringList(Aggregations aggregations, String name) {
        Terms Terms = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = Terms.getBuckets();
        List<String> List = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String str = bucket.getKeyAsString();
            List.add(str);
        }
        return List;
    }
}
